Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
How to call MongoDB CRUD operations from outside of the async run function | JS

The following code is the default async run function for the MongoDB JS driver.

async function run() {
  try {
    await client.connect();
    const database = client.db('sample_mflix');
    const movies = database.collection('movies');
    // Query for a movie that has the title 'Back to the Future'
    const query = { title: 'Back to the Future' };
    const movie = await movies.findOne(query);
    console.log(movie);
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Is there any way on earth to do the CRUD operations etc outside of that function, e.g in an expressjs endpoint?

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can have a function that connects to the DB, probably in a different file and export the function

// DB.js
async function connectToDatabase() {
  try {
    await client.connect();
    return client.db('sample_mflix');
  } catch(err) {
    console.dir(err);
  } finally {
    await client.close();
  }
}

Then import it if you're using the export method, or just call the function

app.get('/api/path', () => {
  const db = await connectToDatabse();

  if (db) {
    const query = {
      title: 'Back to the Future'
    };

    const movie = await db.collection('movies').findOne(query);
    console.log(movie)
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda